var $;
var layer;
var table;
var form;

layui.use(['layer', 'table', 'form'], function () {
    layer = layui.layer;
    $ = layui.jquery;
    table = layui.table;
    form = layui.form;

    getClass();
    getiInitialize();

    //初始化用户信息——表格
    function getiInitialize(){
        $.post("/login/selUserContent", {}, function (res) {
            if (res.code>-1) {
                $("#UserId").val(res.obj.userId);
                $("#UserDept").val(res.obj.deptId);//权限
                getTab(null,"","","",null);
            } else {
                layer.msg("数据加载失败", {icon: 2});
            }
        });
    }

    //查询课程分类
    function getClass(){
        $.ajax({
            url: "/tea/selCourseClass",
            type: "get",
            dataType: "json",
            success: function (data) {
                //初始化树
                ztree(data.obj);
            },
            error: function () {
                layer.msg("数据获取失败！");
            }
        });
    }



    //初始化ztree
    function ztree(data) {
        $(function () {
            var ZtreeTile;
            //右键工具栏
            function OnRightClick(event, treeId, treeNode) {
                if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                    zTree.cancelSelectedNode();
                    showRMenu("root",event.clientX,event.clientY);
                } else if (treeNode && !treeNode.noR) {
                    ZtreeTile = treeNode;
                    showRMenu("node", event.clientX, event.clientY);
                }
            }
            function showRMenu(type, x, y) {
                $("#rMenu ul").show();
                if (type == "root") {
                    $("#m_del").hide();
                    $("#m_check").hide();
                    $("#m_unCheck").hide();
                } else {
                    $("#m_del").show();
                    $("#m_check").show();
                    $("#m_unCheck").show();
                }
                x+=15;
                y+=5;
                rMenu.css({"top": y + "px", "left": x + "px", "display": "block"});
                $("body").bind("mousedown", onBodyMouseDown);
            }

            function hideRMenu() {
                if (rMenu) rMenu.css({"display": "block"});
                $("body").unbind("mousedown", onBodyMouseDown);
            }

            function onBodyMouseDown(event) {
                if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
                    rMenu.css({"display": "block"});
                }
            }

            //添加节点
            $("#m_add").on("click", function () {
                hideRMenu();
                //绑定添加事件，并定义添加操作
                console.log(ZtreeTile);
                var parentId = ZtreeTile.nodeid;
                var uId = $("#UserId").val();
                layer.open({
                    type: 1,
                    title: "添加节点",
                    area: ['400px', '180px'],
                    shade: 0.4,
                    offset: ['100px', '200px'],
                    content: "<div class='layerDiv'><p>分类名称:</p>"
                        + "<input type='text' name='title' required id='treeNode_id' lay-verify='required' placeholder='请输入标题' autocomplete='off' class='layui-input'></div>",
                    btn: ['添加', '取消'],
                    yes: function (index, layero) {
                        var name = $("#treeNode_id").val();
                        $.ajax({
                            url: "/tea/addClassTree",
                            type: "post",
                            dataType: "json",
                            data: {"parentId": parentId, "name": name,"uId":uId},
                            success: function (data) {
                                if (data.code>-1) {
                                    layer.msg("课程添加成功", {icon: 1,time: 1000},function(){
                                        layer.close(index);
                                        location.reload();//刷新页面
                                    });
                                } else {
                                    layer.msg("数据加载失败", {icon: 2});
                                }
                            }
                        })
                    },
                    btn2: function (index, layero) {
                        rMenu.css({"display": "none"});
                        layer.close(index);
                    }
                })
            })
            //修改节点
            $("#m_check").on("click", function () {
                layer.open({
                    type: 1,
                    title: "修改节点",
                    area: ['400px', '180px'],
                    shade: 0.4,
                    offset: ['100px', '200px'],
                    content: "<div class='layerDiv'><p>分类名称:</p>"
                        + "<input type='text' name='title' required id='treeNode_id' value='"+ZtreeTile.menuName+"' lay-verify='required' placeholder='请输入标题' autocomplete='off' class='layui-input'></div>",
                    btn: ['修改', '取消'],
                    yes: function (index, layero) {
                        var id = ZtreeTile.nodeid;
                        var uId = $("#UserId").val();
                        var name = $("#treeNode_id").val();
                        $.ajax({
                            url: "/tea/updClassTree",
                            type: "post",
                            dataType: "json",
                            data: {"id": id, "name": name,"uId":uId},
                            success: function (data) {
                                if (data.code>-1) {
                                    layer.msg("修改成功", {icon: 1,time: 1000},function(){
                                        layer.close(index);
                                        location.reload();//刷新页面
                                    });
                                } else {
                                    layer.msg("数据加载失败", {icon: 2});
                                }
                            }
                        })
                    },
                    btn2: function (index, layero) {
                        rMenu.css({"display": "none"});
                        layer.close(index);
                    }
                })
                hideRMenu();
            })
            //删除节点
            $("#m_del").on("click", function () {
                hideRMenu();
                var id = ZtreeTile.nodeid;
                layer.open({
                    type: 1,
                    title: "删除节点",
                    area: ['200px', '180px'],
                    shade: 0.4,
                    offset:  ['100px', '200px'],
                    content:"<div class='layDiv'><p>确定删除分类<span>"+ZtreeTile.menuName+"</span>吗？</p></div>",
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        $.post("/tea/delClassTree", {id: id}, function (res) {
                            if (res.code>-1) {
                                layer.msg("课程删除成功", {icon: 1,time: 1000},function(){
                                    layer.close(index);
                                    location.reload();//刷新页面
                                });
                            } else {
                                layer.msg("数据加载失败", {icon: 2});
                            }
                        });
                    },
                    btn2: function (index, layero) {
                        rMenu.css({"display": "none"});
                        layer.close(index);
                    }
                })
            })

            function resetTree() {
                hideRMenu();
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
            }

            var zTree, rMenu;
            $(document).ready(function () {
                $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
                zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.expandAll(true);
                rMenu = $("#rMenu");
            });

            var setting = {
                data: {//设置data属性
                    simpleData: {
                        enable: true, //true 、 false 分别表示 使用 、 不使用 简单数据模式
                        idKey: "nodeid", //节点数据中保存唯一标识的属性名称
                        pIdKey: "parentId",   //节点数据中保存其父节点唯一标识的属性名称
                        rootPId: -1 //用于修正根节点父节点数据，即 pIdKey 指定的属性值
                    },
                    key: {
                        name: "menuName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
                    }
                },
                check: {
                    chkStyle: "checkbox",//复选框类型
                    chkboxType: {"Y": "p", "N": "p"},//Y是勾选的时候对父结点或子结点产生的影响;N是取消的时候对父结点或子结点产生的影响;大小写是有区另的。s指子结点，p指父结点
                    enable: false, //true 、 false 分别表示 显示 、不显示 复选框或单选框
                    nocheckInherit: true
                },
                callback: {
                    onRightClick: OnRightClick,
                    onClick: zTreeOnClick,
                    beforeClick: validStatus
                },
                view: {
                    dblClickExpand: false,
                    showIcon: false
                }
            };
            var zTreeNodes = data;
        })

        //禁止父节点点击
        function validStatus(treeId, treeNode, clickFlag) {
            if (treeNode.children.length > 0) {
                layer.msg('不能选择父分类');
                return false;
            }
            return true;
        };
        //点击节点获取值
        function zTreeOnClick(event, treeId, treeNode) {
            getTab(null,"","","",treeNode.nodeid);
            $("#classId").val(treeNode.nodeid);
            return false;
        };
    };

    //获取课程的数据
    function getTab(uId,title,phone,account,classId,likenum,collectnum,hitsnum,sharenum,date,date2){
        $.ajax({
            url:"/tea/selForumTab",
            type:"post",
            dataType:"json",
            contentType:"application/json",
            data:JSON.stringify({"uId":uId,"title":title,"phone":phone,"account":account,"classId":classId,
                "articleLike":likenum,"collectNum":collectnum,"articleHits":hitsnum,"articleShare":sharenum
                ,"createDate":date,"createDate2":date2}),
            success:function(data){
                tab(data.obj);
            },
            error: function () {
                layer.msg('数据获取失败！');
            }
        });
    }

    //表格渲染
    function tab(data) {
        var uDept=$("#UserDept").val();
        if(uDept==4 || uDept==3){//超级管理员&运营
            table.render({
                elem: '#forumTab',
                data:data
                ,toolbar: '#toolbarDemo'//开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: []//自定义头部工具栏右侧图标
                ,title: '个人微圈数据表'
                ,page:true
                ,limit:5
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'microcircleId', title:'ID',hide:true}
                    ,{title:'排序',width:67,fixed:'left',templet(da){//templet 通过这个函数可以实现逻辑处理，比如时间戳的转换
                            return da.LAY_INDEX;/*返回它的序列号*/}}
                    ,{field:'userName', title:'用户昵称',width:86}
                    ,{field:'articleTitle', title:'文章名称',width:160}
                    ,{field:'createDate', title:'创建时间',width:170,templet(da){
                            var createDate=settime(da.createDate);
                            return "<div>"+createDate+"</div>"
                        }}
                    ,{field:'userAccount', title:'用户账号',width:108}
                    ,{field:'articleLike', title:'点赞数',width:76}
                    ,{field:'collectNum', title:'收藏数',width:76}
                    ,{field:'articleHits', title:'查看量',width:76}
                    ,{field:'articleShare', title:'分享量',width:76}
                    ,{title:'操作', width:180,templet(da){
                            return "<p><a onclick='javascript:getMicroCircle("+da.microcircleId+")'>查看</a>" +
                                "<a onclick='javascript:delMicroCircle("+da.microcircleId+")'>删除</a></p>";
                        }}
                ]]
            });
        }else if(uDept==2) {//教师
            table.render({
                elem: '#forumTab',
                data:data
                ,toolbar: '#toolbarDemo'//开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: []//自定义头部工具栏右侧图标
                ,title: '个人微圈数据表'
                ,page:true
                ,limit:5
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    ,{field:'microcircleId', title:'ID',hide:true}
                    ,{title:'排序',width:67,fixed:'left',templet(da){//templet 通过这个函数可以实现逻辑处理，比如时间戳的转换
                            return da.LAY_INDEX;/*返回它的序列号*/}}
                    ,{field:'userName', title:'用户昵称',width:86}
                    ,{field:'articleTitle', title:'文章名称',width:160}
                    ,{field:'createDate', title:'创建时间',width:170,templet(da){
                            var createDate=settime(da.createDate);
                            return "<div>"+createDate+"</div>"
                        }}
                    ,{field:'userAccount', title:'用户账号',width:108}
                    ,{field:'articleLike', title:'点赞数'}
                    ,{field:'collectNum', title:'收藏数'}
                    ,{field:'articleHits', title:'查看量'}
                    ,{field:'articleShare', title:'分享量'}
                    ,{title:'操作', width:90,templet(da){
                            return "<p><a onclick='javascript:getMicroCircle("+da.microcircleId+")'>查看</a></p>";
                        }}
                ]]
            });
        }
    }

    /*日期转换*/
    function settime(da){
        var date=new Date(da);
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hours=date.getHours();
        var mm=date.getMinutes();
        var s=date.getSeconds();
        return year+'-'+add(month)+'-'+add(day)+' '+add(hours)+':'+add(mm)+':'+add(s);
        //return year+'-'+month+'-'+day+' '+hours+':'+mm+':'+s;
    };
    function add(time){//给非整数添0
        return time<10?'0'+time:time;
    };

    //查询按钮
    $("#queryButId").on("click",function(){
        var title=$("#title").val();
        var phone=$("#phone").val();
        var account=$("#account").val();
        getTab(null,title,phone,account,null);
    });

    //高级检索
    $("#retrievalButId").on("click",function(){
        layer.open({
            type:2,
            title:"高级检索",
            area:['550px','400px'],
            shade:0.4,
            offset:'auto',
            content:"MCRretrieval.html"
        });
        window.layer_3=layer;//将当前弹出层的对象赋值给window对象
    });
    //检索出的表格
    setTab =function () {
        var uphone=$("#uphone").val();
        var date=$("#createDate").val();//开始时间
        var date2=$("#createDate2").val();//结束时间
        var likenum=$("#articleLike").val();
        var collectnum=$("#collectNum").val();
        var hitsnum=$("#articleHits").val();
        var sharenum=$("#articleShare").val();
        getTab(null,"",uphone,"",null,likenum,collectnum,hitsnum,sharenum,date,date2);
    };
});



//查看-编辑微圈
function getMicroCircle(id) {
    layer.open({
        type:2,
        title:"微圈管理",
        area:['1200px','600px'],
        shade:0.4,
        offset:['10px','100px'],
        maxmin: true,
        content:"TeaManageMC.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('input[name=mcId]').val(id);
        }
    });
    window.layer_4=layer;
};

//删除微圈
function delMicroCircle(id) {
    layer.open({
        type: 1,
        title: "删除文章",
        area: ['200px', '200px'],
        shade: 0.4,
        offset: 'auto',
        content:"<p id='layerpId'>确定删除该文章吗？</p>",
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            $.post("/tea/delMicroCircle", {id: id}, function (res) {
                if (res.code>-1) {
                    layer.msg("删除成功", {icon: 1},function(){
                        layer.close(index);
                        location.reload();//刷新页面
                    });
                } else {
                    layer.msg("数据加载失败", {icon: 2});
                }
            });
        },
        btn2: function (index, layero) {
            layer.close(index);
        }
    })
}

//添加微圈文章
function addMC() {
    var classId=$("#classId").val();
    layer.open({
        type:2,
        title:"添加文章",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"TeaAddMC.html?classId="+classId,//设置的速度赶不上获取的速度，结果获取不到值
        success:function(layero,index) {
            var obj = layero.find('iframe').contents();
            var uId=$("#UserId").val();
            obj.find('input[name=userId]').val(uId);
        },
        end:function () {
            location.reload();
        }
    });
    //将当前弹出层的对象赋值给window对象
    window.layer_3=layer;
};

//刷新按钮
$("#breakbtn").on("click",function () {
    location.reload();//刷新页面
});
//返回按钮
$("#returnbtn").on("click",function () {
    history.go(-1);//数据全部还在 //history.back(-1)//直接返回当前页的上一页，是个新页面
});

//重置按钮
$("#resetButId").on("click",function () {
    $("#title").val("");
    $("#phone").val("");
    $("#account").val("");
    getTab(null,"","","",null);
});